/**
 * 右键菜单插件类；
 */
define(function (require, exports, module) {
    /**
     * Right context menu plugin
     * @param {WebPDF.ReaderApp} readerApp app instance
     * @extends {WebPDF.IReaderPlugin}
     * @constructor
     */
	WebPDF.CONTEXTMENU_PLUGIN_NAME = "ContextMenu Plugin";
	
    WebPDF.ContextMenuPlugin = function (readerApp) {
        var _readerApp = readerApp,
            _menuContainerID = _readerApp.getAppId() + "FxMenuContainer",
            _menuID = _readerApp.getAppId() + "FxMenu",
            _isMenuVisible = false,
            _self = this;
        	

        //获取Plugin名称;
        this.getPluginName = function () {
            return WebPDF.CONTEXTMENU_PLUGIN_NAME;
        };

        //插件被注册的时候调用;
        this.onRegister = function () {
        };
        

        //模块初始化;
        this.init = function () {
            var menuHtml = "<div id='" + _menuContainerID + "'><ul id='" + _menuID
                + "' class='fwrContextMenu fwr_cm_default' style='display: none;'></div>";
            var mainView = _readerApp.getMainView();
            $("#" + mainView.getMainFrameID()).after(menuHtml);
            _createCmdAndMenuItem();
            var menuItemsHtml = "";
            var menuBar = WebPDF.Config.MenuBar;                
            var menuItems = menuBar['document'].items;
            for (var k = 0; k < menuItems.length; k++) {               
                 menuItemsHtml += _self.createMenuItemHtml(menuItems[k]);
             }  
               
            
            $("#" + _menuID).append(menuItemsHtml);

            $("#" + mainView.getDocView().getDocViewContainerID()).on('contextmenu',
                function () {
                    if (_isMenuVisible) _self.hiddenMenu();
                    return false;
                }
            ).fwrContextMenu(_menuID, {
                    onSelect: function (e, context) {                      
                        return _self.onSelect($(this));
                    },
                    onShow: function (e, context) {
                        $("#" + _menuID).i18n();
                        return _self.onShow($(this));
                    },
                    onHide: function (e, context) {
                        return _self.onHidden();
                    },
                    onHover: function (e, context) {
                        return true;
                    }
                },document.getElementById(mainView.getMainFrameID()));
        };

        /**
         * Create html for menus.
         * @param jsonMenuItem menu data in JSON format
         * @returns {String}
         */
        this.createMenuItemHtml = function(jsonMenuItem) {
            var menuItemHtml = "";
            if (!jsonMenuItem) return "";
            if (!jsonMenuItem.enable) return "";
            
            var pMenuItem = _readerApp.getMenuItem(jsonMenuItem.item);
            if (!pMenuItem) return "";
            
            menuItemHtml = pMenuItem.createHtml();
            if (menuItemHtml === "")
                return menuItemHtml;
            
            var jqMenuItem = $(menuItemHtml);
            var hasSubItem = false;
            var subItemsHtml = "";
            if (jsonMenuItem.subitems && jsonMenuItem.subitems.length > 0) {
                for (var i = 0; i < jsonMenuItem.subitems.length; i++) {
                    var jsonChildMenuItem = jsonMenuItem.subitems[i];
                    var childMenuHtml = _self.createMenuItemHtml(jsonChildMenuItem);
                    if (childMenuHtml != "") {
                        hasSubItem = true;
                        subItemsHtml += childMenuHtml;
                    }
                }
            }
            if (hasSubItem) {
                jqMenuItem.append("<ul>" + subItemsHtml + "</ul>");
            }
            menuItemHtml = jqMenuItem.get(0).outerHTML;
            return menuItemHtml;
        }


        //模块卸载;
        this.unLoad = function () {
        };

        this.getReaderApp = function () {
            return _readerApp;
        };
        


        /**
         * Create menus
         * @private
         */
        function _createCmdAndMenuItem() {
            var appId = _readerApp.getAppId();           
            var docView = _readerApp.getMainView().getDocView();
            _readerApp.addMenuItem({
                name: "MenuSeparator",
                createHtml: function () {
                    return "<li class='separator'></li>";
                }
            });
            _readerApp.addMenuItem({
                name: "MenuReadMode",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuReadMode'><span class='icon'>Read Mode</span></li>";
                },
                onShow: function(jqMenuItem) {          
                    jqMenuItem.addClass('disabled');   
                },
                onSelect: function (jqMenuItem) {                   
                }
            });
            _readerApp.addMenuItem({
                name: "MenuFullScreen",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuFullScreen'><span class='icon'>Full Screen</span></li>";
                },
                onShow: function (jqMenuItem) {     
                    jqMenuItem.addClass('disabled');   
                },
                onSelect: function (jqMenuItem) {                    
                }
            });
            _readerApp.addMenuItem({
                name: "MenuZoomIn",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuZoomIn'><span class='zoomin_16 icon'>Zoom In</span></li>";
                },
                onShow: function (jqMenuItem) {     
                    var currentZoom = docView.getScale();
                    var scaleList = docView.getCurrentScaleList();
                    if (currentZoom < scaleList[scaleList.length-1])     {
                        jqMenuItem.removeClass('disabled');   
                    }
                    else{
                         jqMenuItem.addClass('disabled');   
                    }
                   
                },
                onSelect: function (jqMenuItem) {       
                    docView.zoomIn();
                }
            });
            _readerApp.addMenuItem({
                name: "MenuZoomOut",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuZoomOut'><span class='zoomout_16 icon'>Zoom Out</span></li>";
                },
                onShow: function (jqMenuItem) {        
                   var currentZoom = docView.getScale();
                    var scaleList = docView.getCurrentScaleList();
                    if (currentZoom > scaleList[0]){
                        jqMenuItem.removeClass('disabled');   
                    }
                    else{
                        jqMenuItem.addClass('disabled');   
                    }
                   
                },
                onSelect: function (jqMenuItem) {   
                    docView.zoomOut();
                }
            });
            _readerApp.addMenuItem({
                name: "MenuActualSize",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuActualSize'><span class='actualsize_16 icon'>Actual Size</span></li>";
                },
                onShow: function (jqMenuItem) {                                     
                    if (docView.isActualSize()){
                        jqMenuItem.addClass('disabled');   
                    }
                    else{
                        jqMenuItem.removeClass('disabled');   
                    }
                },
                onSelect: function (jqMenuItem) {      
                    docView.actualSize();
                }
            });
            _readerApp.addMenuItem({
                name: "MenuFitPage",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuFitPage'><span class='fitpage icon'>Fit Page</span></li>";
                },
                onShow: function (jqMenuItem) {    
                    if (docView.isFitPage()){
                        jqMenuItem.addClass('disabled');   
                    }
                    else{
                        jqMenuItem.removeClass('disabled');   
                    }
                },
                onSelect: function (jqMenuItem) {   
                    docView.fitPage();
                }
            });

            _readerApp.addMenuItem({
                name: "MenuFitWidth",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuFitWidth'><span class='fitwidth_16 icon'>Fit Width</span></li>";
                },
                onShow: function (jqMenuItem) {                                     
                    if (docView.isFitWidth()){
                        jqMenuItem.addClass('disabled');   
                    }
                    else{
                        jqMenuItem.removeClass('disabled');   
                    }
                },
                onSelect: function (jqMenuItem) {      
                    docView.fitWidth();
                }
            });

            _readerApp.addMenuItem({
                name: "MenuFitVisible",
                createHtml: function () {
                    return "<li  class='icon' menuname='MenuFitVisible'><span class='icon fitvisible'>Fit Visible</span></li>";
                },
                onShow: function (jqMenuItem) {     
                   jqMenuItem.addClass('disabled');   
                },
                onSelect: function (jqMenuItem) {                    
                }
            });
            _readerApp.addMenuItem({
                name: "MenuRotateLeft",
                createHtml: function () {
                    return "<li  class='icon' menuname='MenuRotateLeft'><span class='icon rotateleft'>Rotate Left</span></li>";
                },
                onShow: function (jqMenuItem) {
                   jqMenuItem.addClass('disabled');   
                },
                onSelect: function (jqMenuItem) {                   
                }
            });
            _readerApp.addMenuItem({
                name: "MenuRotateRight",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuRotateRight'><span class='icon rotateright'>Rotate Right</span></li>";
                },
                onShow: function (jqMenuItem) {
                    jqMenuItem.addClass('disabled');   
                },
                onSelect: function (jqMenuItem) {                   
                }
            });
            
            _readerApp.addMenuItem({
                name: "MenuGetALink",
                createHtml: function () {
                    return "<li class='icon' menuname='MenuGetALink'><span class='icon icon1'>Get A Link</span></li>";
                },
                onShow: function (jqMenuItem) {
                   jqMenuItem.addClass('disabled');   
                },
                onSelect: function (jqMenuItem) {                   
                }
            });
        }

        /**
         * hide menu
         * @private
         */
        this.hiddenMenu = function() {
            $("#" + _menuID).trigger('click.fwrContextMenu');
        }

        /**
         * Trigger when the menu is hidden.
         * @private
         */
        this.onHidden = function() {
            _isMenuVisible = false;
        }      
        

        /**
         * trigger when menu shown.
         * @private
         */
        this.onShow = function(jqMenu) {
            _isMenuVisible = true;
            
            jqMenu.find("[menuname]").each(function(){             
                var menuName = $(this).attr("menuname");
                var menuItem = _readerApp.getMenuItem(menuName);
                if (menuItem) {
                     menuItem.onShow($(this));
                }
            })                                           
        }

        /**
         * Trigger when user select a menu item.
         * @param {WebPDF.CMenuItem} jqMenuItem the menu item which selected
         * @private
         */
        this.onSelect = function(jqMenuItem) {
            if (jqMenuItem != null) {
                try {
                    var menuName = jqMenuItem.attr("menuname");
                    var menuItem = _readerApp.getMenuItem(menuName);
                    if (menuItem) {
                        menuItem.onSelect(jqMenuItem);
                    }
                }
                catch (ex) {
                    console.error(ex);
                }
            }
        }
    };

    exports.createPlugin = function (readerApp) {
        return new WebPDF.ContextMenuPlugin(readerApp);
    };
});
